package online.szlib.com.web.controller;

import java.io.IOException;
import java.io.OutputStream;
import java.security.SecureRandom;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONObject;
import online.szlib.com.common.utils.Constants;
import online.szlib.com.common.utils.ImageHelper;
import online.szlib.com.common.utils.JSONHelper;
import online.szlib.com.core.domain.User;
import online.szlib.com.core.services.UserService;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class LogInController {

    private static Logger logger = LoggerFactory.getLogger(LogInController.class);

	private static final String IMG_TYPE = "image/jpeg";
	
    @Autowired
    private UserService userService;
	
	// Http get Login
	@RequestMapping(value="login", method = RequestMethod.GET)
	public ModelAndView goLogin(HttpServletRequest request, HttpServletResponse response) {
		Map<String, Object> model = new HashMap<String, Object>();
//		localeResolver.setLocale(request, response, Locale.CHINA);
		return new ModelAndView("loginLayout", model);
	}
	
	@RequestMapping(value = "/login", params={"type=object"}, method = RequestMethod.POST)
	public ResponseEntity<JSONObject> login(@RequestBody User loginUser) {
		User user = userService.login(loginUser.getUserName(), loginUser.getPassword());
		JSONObject json = new JSONObject();
		json.put("success", user != null);
		return new ResponseEntity<JSONObject>(json, JSONHelper.getJSONHeaders(), HttpStatus.OK);
	}
	
	@RequestMapping(value = "/login", params={"type=txt"}, method = RequestMethod.POST)
	public ModelAndView login(@RequestBody String loginStr) {
		User user = userService.login("admin", "pass");
		if (user != null) {
			return new ModelAndView("redirect:/myHome");
		} else {
			return new ModelAndView("loginLayout");
		}
	}
	
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public ModelAndView login(@RequestParam String username, @RequestParam String password) {
		User user = userService.login(username, password);
		if (user != null) {
			return new ModelAndView("redirect:/myHome");
		} else {
			return new ModelAndView("loginLayout");
		}
	}
	
	@RequestMapping(value="/geneImgCode", method = RequestMethod.GET)
	public void generateImageCode(HttpServletRequest request, HttpServletResponse response) {
		response.setContentType(IMG_TYPE);
        Random random = new SecureRandom();
        try {
            OutputStream outputStream = response.getOutputStream();
            String registrationCode = ImageHelper.generateCode(random);
            ImageHelper.output(outputStream, registrationCode, random);
            outputStream.flush();
            request.getSession().setAttribute(Constants.SESSION_KEY, registrationCode);
        } catch (IOException ioe) {
        	logger.debug("Error generating image.", ioe);
        }
	}
	
	@RequestMapping(value="/logout", method = RequestMethod.GET)
	public ModelAndView goLogOff(HttpServletRequest request, HttpServletResponse response) {
		Map<String, Object> model = new HashMap<String, Object>();
		HttpSession session = request.getSession();
		session.removeAttribute(Constants.TOKEN);
		session.removeAttribute(Constants.SESSION_KEY);
		session.invalidate();
		return new ModelAndView("loginLayout", model);
	}
}
